import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';

dayjs.extend(utc);
dayjs.extend(timezone);

export const formatDataNoTime = (time: string) => {
  return dayjs.utc(time).tz('Asia/Shanghai').format('YYYY-MM-DD');
};
export const formatData = (time: string) => {
  return dayjs.utc(time).tz('Asia/Shanghai').format('YYYY.MM.DD HH:mm');
};

export const formatDataWithSeconds = (time: string) => {
  return dayjs.utc(time).tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss');
};

export function getRelativeTimeString(text: string): string {
  // 尝试从文本中提取时间部分
  const timeMatch = text.match(/\d{4}[-/]\d{1,2}[-/]\d{1,2}([T\s]\d{1,2}:\d{1,2}(:\d{1,2})?)?/);
  if (!timeMatch) {
    // 如果没有找到时间格式，返回原文本
    return text;
  }

  const dateStr = timeMatch[0];
  const date = new Date(dateStr);

  // 如果日期无效，返回原文本
  if (isNaN(date.getTime())) {
    return text;
  }

  const now = new Date();
  const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);

  let timeText;
  if (diffInSeconds < 60) {
    timeText = `${diffInSeconds}秒前`;
  } else {
    const diffInMinutes = Math.floor(diffInSeconds / 60);
    if (diffInMinutes < 60) {
      timeText = `${diffInMinutes}分钟前`;
    } else {
      const diffInHours = Math.floor(diffInMinutes / 60);
      if (diffInHours < 24) {
        timeText = `${diffInHours}小时前`;
      } else {
        const diffInDays = Math.floor(diffInHours / 24);
        timeText = `${diffInDays}天前`;
      }
    }
  }

  // 替换原文本中的时间部分为相对时间
  return text.replace(dateStr, timeText);
}

/**
 * 获取当前时间段的问候语
 * @returns {string} 早上好/中午好/下午好/晚上好
 */
export function getTimePeriod(): string {
  const hour = dayjs().tz('Asia/Shanghai').hour();
  if (hour >= 5 && hour < 12) {
    return '早上好';
  } else if (hour >= 12 && hour < 14) {
    return '中午好';
  } else if (hour >= 14 && hour < 18) {
    return '下午好';
  } else {
    return '晚上好';
  }
}
